<template>
  <div>
    <el-drawer
      title="选择素材"
      size="65%"
      :visible.sync="drawerShow"
      :modal-append-to-body="false"
      :modal="false"
      :close-on-click-modal="false"
      :append-to-body="false"
      :wrapperClosable="false"
      @close="handleClose"
    >
      <el-divider></el-divider>
      <cs-drawer-container id="creative-drawer-aco">
        <div class="creative-drawer-box" id="creative-drawer-box-aco">
          <el-form :inline="true" :model="creativeDrawerQueryForm" class="demo-form-inline">
            <el-form-item label="短ID">
              <el-input style="width:270px" size="mini" v-model="creativeDrawerQueryForm.stringShortId"
                        placeholder="请输入短ID"></el-input>
            </el-form-item>
            <el-form-item label="本地文件名">
              <el-input style="width:220px" size="mini" v-model="creativeDrawerQueryForm.localFilename"
                        placeholder="请输入本地文件名"></el-input>
            </el-form-item>
            <el-form-item label="素材名称">
              <el-input style="width:220px" size="mini" v-model="creativeDrawerQueryForm.name"
                        placeholder="请输入素材名称"></el-input>
            </el-form-item>
            <el-form-item label="需求名称">
              <el-input style="width:240px" size="mini" v-model="creativeDrawerQueryForm.requestName"
                        placeholder="请输入需求名称"></el-input>
            </el-form-item>
            <el-form-item label="素材尺寸">
              <el-select style="width: 140px" v-model="creativeDrawerQueryForm.sizeType" clearable placeholder="请选择素材尺寸"
                         size="mini">
                <el-option
                  v-for="item in sizeType"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="设计师">
              <el-select style="width: 130px" v-model="creativeDrawerQueryForm.designer" clearable filterable
                         size="mini"
                         placeholder="请选择设计师">
                <el-option
                  v-for="item in designersList"
                  :key="item.value"
                  :label="item.realName"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="类型">
              <el-select style="width: 125px" size="mini" v-model="creativeDrawerQueryForm.type" placeholder="类型">
                <el-option label="图片" :value="0"></el-option>
                <el-option label="视频" :value="1"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="上传时间">
              <el-date-picker
                size="mini"
                v-model="creativeDrawerQueryForm.date"
                type="daterange"
                range-separator="至"
                value-format="yyyy-MM-dd"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                @change="handleChangeCreativeDate">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="审批通过时间">
              <el-date-picker
                size="mini"
                v-model="creativeDrawerQueryForm.beginAuditDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="包含此时间以后的记录">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="状态">
              <el-select v-model="creativeDrawerQueryForm.strStatus" clearable filterable multiple
                         size="mini"
                         placeholder="请选择状态">
                <el-option
                  v-for="item in approvalStatusList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item class="clear-4">
              <el-button size="mini" @click="clearCreativeQuery">清空</el-button>
              <el-button size="mini" type="primary" @click="getCreativeTabelData">查询</el-button>
            </el-form-item>
          </el-form>
          <div class="curd-table" id="curd-table-1">
            <div class="table-body">
              <el-table
                ref="acoCreativeTable"
                :data="creativeTableData"
                tooltip-effect="dark"
                height="calc(100vh - 380px)"
                style="width: 100%"
                :row-key="(row) => row.id"
                v-loading="creativeLoading"
                @selection-change="handleCreativeSelectionChange">
                <el-table-column
                  type="selection"
                  :reserve-selection="true"
                  width="55">
                </el-table-column>
                <el-table-column
                  label="素材">
                  <template v-slot="{row}">
                    <el-tooltip effect="dark" content="点击预览素材" placement="bottom-end">
                      <div style="display: inline-block;cursor: pointer;"
                           :class="row.type == 1?'play-icon':''">
                        <video
                          v-if="row.type == 1"
                          style="width: 100px; height: 100px"
                          :src="row.creativeUrl"
                          @click="handlePreview(row)"
                        >
                        </video>
                        <el-image
                          v-else
                          style="width: 100px; height: 100px"
                          :src="row.creativeUrl"
                          :fit="'cover'"
                          @click="handlePreview(row)"
                        >
                        </el-image>
                      </div>
                    </el-tooltip>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="shortId"
                  label="短ID"
                  show-overflow-tooltip>
                </el-table-column>
                <el-table-column
                  prop="localFilename"
                  label="本地文件名"
                  show-overflow-tooltip>
                </el-table-column>
                <el-table-column
                  prop="name"
                  label="素材名称"
                  show-overflow-tooltip>
                </el-table-column>
                <el-table-column
                  prop="type"
                  :formatter="formatterCreativeType"
                  label="类型"
                  show-overflow-tooltip>
                </el-table-column>
                <el-table-column
                  prop="auditTime"
                  label="审批通过时间"
                  show-overflow-tooltip>
                </el-table-column>
              </el-table>
            </div>
            <div class="bottom-page clearfix">
              <el-pagination
                background
                @size-change="handleCreativeSizeChange"
                @current-change="handleCreativeCurrentChange"
                :current-page="creativePage.currentPage"
                :page-sizes="[10, 20, 30, 40, 50, 100]"
                :page-size="creativePage.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="creativeDrawerTotal">
              </el-pagination>
            </div>
          </div>
        </div>
        <el-button slot="bottom" size="mini" @click="drawerShow=false" id="uploadFrom-1">取消</el-button>
        <el-button slot="bottom" size="mini" type="primary" @click="submitCreative" id="submitCre-1">确定</el-button>
      </cs-drawer-container>
    </el-drawer>
    <creative-card-preview v-model="assetPreview" :media-preview="previewCreative">
    </creative-card-preview>
  </div>
</template>

<script>
import {getAllUser} from "@/api/user";
import CsDrawerContainer from "@/components/CsDrawerContainer/CsDrawerContainer";
import {offerCreativePage} from "@/api/campaign-management/campaign-management";
import CreativeCardPreview from "../../../components/CreativeCardPreview/CreativeCardPreview";
import _ from "lodash";

export default {
  name: "CreativeSelectDrawer",
  components: {
    CsDrawerContainer,
    CreativeCardPreview
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    offerId: {
      type: String
    },
    creativeList: {
      type: Array
    }
  },
  computed: {
    drawerShow: {
      get() {
        // this.handleOpenDrawer()
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val || false)
      }
    },
  },
  data() {
    return {
      assetPreview: false,
      previewCreative: null,
      creativeDrawerTotal: 0,
      creativeLoading: false,
      creativeTableData: [],
      designersList: [],
      multipleCreativeSelection: [],
      sizeType: [
        {label: "横幅", value: 'H'},
        {label: "竖幅", value: 'V'},
        {label: "方幅", value: 'S'},
      ],
      approvalStatusList: [
        {label: "等待提交", value: 0},
        {label: "等待审核", value: 1},
        {label: "审核通过", value: 2},
        {label: "审核拒绝", value: 3},
        {label: "禁用", value: 4},
      ],
      creativeDrawerQueryForm: {
        stringShortId: '',
        localFilename: '',
        name: '',
        type: '',
        date: '',
        beginDate: null,
        endDate: null,
        sizeType: '',
        requestName: '',
        strStatus: [1,2],
        designer: '',
        beginAuditDate: ''
      },
      creativePage: {
        current: 1,
        size: 10
      }
    }
  },
  created() {
    getAllUser({statusList: '0,1,2', isAll: true}).then((res) => {
      this.designersList = res.data.data;
    });
    this.getCreativeTabelData()
  },
  methods: {
    submitCreative() {
      const arr = _.cloneDeep(this.creativeList.concat(this.multipleCreativeSelection.map(item => {
        return item
      })))
      let newArr = arr.reduce((pre, cur) => {
        if (!pre.some(item => item.id === cur.id)) {
          return pre.concat(cur)
        } else {
          return pre
        }
      }, [])
      if (newArr.length > 30) return this.$message.warning('程序化创意素材不能超过30个')
      this.$emit("changeCreatives", newArr)
      this.multipleCreativeSelection = []
      this.drawerShow = false
    },
    formatterCreativeType(row, column, cellValue, index) {
      if (cellValue == 0) {
        return '图片'
      } else {
        return '视频'
      }
    },
    clearCreativeQuery() {
      this.creativeDrawerQueryForm = {
        shortId: '',
        localFilename: '',
        name: '',
        date: '',
        beginDate: null,
        endDate: null,
        sizeType: '',
        requestName: '',
        strStatus: [1,2],
        designer: '',
        beginAuditDate: ''
      }
      this.getCreativeTabelData()
    },
    handleCreativeSizeChange(val) {
      this.creativePage.size = val
      this.creativePage.current = 1
      this.getCreativeTabelData()
    },
    handleCreativeCurrentChange(val) {
      this.creativePage.current = val
      this.getCreativeTabelData()
    },
    handleCreativeSelectionChange(val) {
      this.multipleCreativeSelection = val
    },
    async getCreativeTabelData() {
      this.creativeLoading = true
      const creativeDrawerQueryForm = _.cloneDeep(this.creativeDrawerQueryForm)
      creativeDrawerQueryForm.strStatus = creativeDrawerQueryForm.strStatus.join(',')
      const {data: res} = await offerCreativePage(
        {
          offerId: this.offerId,
          platform: 'tiktok',
          ...this.creativePage,
          ...creativeDrawerQueryForm
        }
      ).finally(() => {
        this.creativeLoading = false
      })
      this.creativeTableData = res.data.records
      this.creativeDrawerTotal = res.data.total
      if (this.drawerShow) {
        this.multipleCreativeSelection = []
        this.creativeList.forEach(item => {
          let row = this.creativeTableData.find(itm => itm.id === item.id)
          if (row !== undefined && row !== null) {
            console.log("row,", row)
            this.multipleCreativeSelection.push(row)
          }
        })
        this.initSelection()
      }
    },
    handleChangeCreativeDate(val) {
      if (val !== null) {
        this.creativeDrawerQueryForm.beginDate = val[0]
        this.creativeDrawerQueryForm.endDate = val[0]
      } else {
        this.creativeDrawerQueryForm.beginDate = null
        this.creativeDrawerQueryForm.endDate = null
      }
    },
    handlePreview(row) {
      this.previewCreative = _.cloneDeep(row)
      this.assetPreview = true
    },
    initSelection() {
      this.multipleCreativeSelection.forEach(rw => {
        this.creativeTableData.forEach(item => {
          if (item.id === rw.id) {
            this.$refs.acoCreativeTable.toggleRowSelection(item, true)
          } else {
            let row = this.creativeList.find(itm => itm.id === item.id)
            if (row === undefined || row === null) {
              this.$refs.acoCreativeTable.toggleRowSelection(item, false)
            }
          }
        })
      })
    },
    handleClose() {
      this.creativeDrawerQueryForm = {
        shortId: '',
        localFilename: '',
        name: '',
        type: '',
        date: '',
        beginDate: null,
        endDate: null,
        sizeType: '',
        requestName: '',
        strStatus: [1,2],
        designer: '',
        beginAuditDate: ''
      }
      this.creativeLoading = false
      this.multipleCreativeSelection = []
      this.creativeTableData = []
      this.previewCreative = null
      this.drawerShow = false
    }
  }
}
</script>
<style lang="scss" scoped>
.creative-drawer-box {
  padding: 0 15px;

  .demo-form-inline {
    .el-select, .el-input {
      width: 150px;
    }

    ::v-deep .el-form-item__label {
      padding: 0 12px 0 0 !important;
    }
  }

  .bottom-page {
    margin-top: 15px;

    .el-pagination {
      float: right;
    }
  }
}
</style>
